import re
from db import db1
from flask import Blueprint,request,jsonify
import json
bp_course = Blueprint('course',__name__)


def xtree(data):
    if not data:
        return data
    tree={}
    list=[]
    for i in data:
        tree[i['id']]=i
    for j in data:
        pid = j['pid']
        if pid==0:
            list.append(j)
        else:
            if 'son' not in tree[pid]:
                tree[pid]['son']=[]
            tree[pid]['son'].append(j)
    return list

@bp_course.route('/cateM',methods=['POST','GET'])
def cateM():
    if request.method=='POST':
        data = request.data
        if data:
            data = json.loads(data)
        else:
            data = request.form
        sql = "insert into cates values(0,'%s',%d,%s)"%(data['name'],int(data['pid']),data['params'])
        print(sql)
        db1.update(sql)
        return jsonify({'code':200})
    else:
        sql = "select * from cates"
        res= db1.findall(sql)
        list = xtree(res)
        return jsonify({'code':200,'list':list}) 


@bp_course.route('/pagecates')
def pagecates():
    # 每个页面显示多少条
    page_size=3
    page = int(request.args.get('page'))
    start = (page-1)*page_size
    sql = "select * from cates order by id asc limit %d,%d"%(start,page_size)
    res = db1.findall(sql)
    sql1 = "select count(id) as total from cates "
    res1 = db1.find(sql1)
    return jsonify({'code':200,'list':res,'total':res1['total']})